package com.khotyn.heresy.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.khotyn.heresy.bean.HeresyErrorMessage;
import com.khotyn.heresy.bean.PagedBean;
import com.khotyn.heresy.ibatis.PictureDAOIbatisImpl;
import com.khotyn.heresy.ibatis.UserDAOIbatisImpl;
import com.khotyn.heresy.util.KeywordFilter;

/**
 * 处理搜索的控制器
 * 
 * @author 王长乐
 * 
 */
@Controller
public class SearchController {

	@Autowired
	private UserDAOIbatisImpl userDAO;
	@Autowired
	private PictureDAOIbatisImpl pictureDAO;

	private static int pageSize = 10;

	@RequestMapping(value = "/search.html", method = RequestMethod.POST)
	public ModelAndView onSubmit(@RequestParam(value = "searchContent", required = true) String searchContent,
			@RequestParam(value = "searchType", required = true) String searchType, @RequestParam(value = "page", required = false) String pageStr) {

		HeresyErrorMessage message = null;

		if (pageStr == null) {
			pageStr = "1";
		}
		// 非法的参数
		if (!KeywordFilter.isNumeric(pageStr)) {
			message = new HeresyErrorMessage("非法的参数", "操作失败", "/Dragonfly/");
			return new ModelAndView("message", "message", message);
		}

		if ("user".equals(searchType)) {

			int page = Integer.parseInt(pageStr);
			PagedBean pagedBean = new PagedBean();
			pagedBean.setPageNum(page);
			pagedBean.setPageSize(pageSize);

			int minRow = (page - 1) * pageSize + 1;
			int maxRow = page * pageSize;
			pagedBean.setPagedItem(userDAO.selectPagedUserBriefInfo(searchContent, minRow, maxRow));
			pagedBean.setItemNum(userDAO.selectUserCountByUserName(searchContent));

			int maxPage = (int) java.lang.Math.ceil((double) pagedBean.getItemNum() / (double) pageSize);
			pagedBean.setMaxPage(maxPage);

			PagedBean userList = pagedBean;
			return new ModelAndView("searchResult", "userList", userList);
		} else if ("picture".equals(searchType)) {
			int page = Integer.parseInt(pageStr);
			PagedBean pagedBean = new PagedBean();
			pagedBean.setPageNum(page);
			pagedBean.setPageSize(pageSize);

			int minRow = (page - 1) * pageSize + 1;
			int maxRow = page * pageSize;
			pagedBean.setPagedItem(pictureDAO.selectPicBriefByPicName(searchContent, minRow, maxRow));
			pagedBean.setItemNum(pictureDAO.selectPicCountByPicName(searchContent));

			int maxPage = (int) java.lang.Math.ceil((double) pagedBean.getItemNum() / (double) pageSize);
			pagedBean.setMaxPage(maxPage);

			PagedBean pictureList = pagedBean;
			return new ModelAndView("searchResult", "pictureList", pictureList);

		}

		return new ModelAndView("user");

	}
}
